
const mongoose = require('mongoose');
var express = require('express')
// 注意这里的声明
var userRoles = express()
// const controller= require("../../controller/controllerenter");

const { userRolesService } = require('../../service/impl/userRolesService');
const { baseSendDatas} = require('../../beans/baseSendDatas');
// const { userRolesBean } = require('../../beans/impl/userRolesBean');
const {createResponse}= require("../../util/createResponse/index");
const {businessCodes}= require("../../code/businessCodes/index");



//#region  用户角色和权限
// 根据文档id删除文档
  userRoles.post('/post/userRoles/delete', async (req,res) => {
    let result
    try {
    let  id  = req.body.conditions.id
      result =  await userRolesService.getIns().findByIdAndDelete(id)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })
  

  // 根据id,修改
  userRoles.post('/post/userRoles/update', async (req,res) => {
    let result
 
    try {
      let id  = req.body.conditions.id
      let updates = req.body.updates
      result =  await userRolesService.getIns().findByIdAndUpdate(id,updates)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })
  
  // 查询所有用户的所有角色
  userRoles.post('/post/userRoles/queryAll', async (req,res) => {
    let result
    let fills = {
      "key1":{
        "path":"appRoles_arr.roleID",
        "populate":{
          "path":"roleAuths_arr.auth_ref"
        }
      },
      "key2":{
       "path":"userID"  
      },
      "key3":{
        "path":"appDynamicsAuths_arr.authID"
      },
      "key4":{
        "path":"companyRoles_arr.roleID",
      },
      "key5":{
        "path":"companyRoles_arr.companyID",
      }
    }
    try {
        result =  await userRolesService.getIns().find(null,null,fills)
    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    }
    createResponse(res,200,businessCodes.b1,result)
  })

 


  // 查询指定用户的角色和权限信息
  userRoles.post('/post/userRoles/findRolesAuthsByUserid', async (req,res) => {
    let result 
    let combinedAuths = [];
    let data

    try {
      let  conditions = {
        userID:req.body.conditions.userID
      }
      let fills ={
        "key1":{   
          path:"appDynamicsAuths_arr.authID"
      },
      "key2":{
        path:"companyRoles_arr.roleID",
        "populate":{
          "path":"roleAuths_arr.auth_ref"
        }
      },
      "key3":{
        path:"companyRoles_arr.companyID",
      },
      "key4":{
        "path":"appRoles_arr.roleID",
        "populate":{
          "path":"roleAuths_arr.auth_ref"
        }
      },
    }

      result =  await userRolesService.getIns().findOne(conditions,null,fills)

      

      if(result==null){
        throw new Error('没有找到用户')
      }
      // 获取数据
 data =result.toObject()

// 从用户的角色中得到权限，放入 combinedAuths 数组里
data.appRoles_arr.forEach(role => {
  role.roleID.roleAuths_arr.forEach(auth => {
    let newAuth = {
      auth_id: auth.auth_ref._id,
      auth_name: auth.auth_ref.auth_name,
      auth_enable: auth.auth_enable,
      auth_desc: auth.auth_ref.auth_desc,
      auth_auth_number: auth.auth_ref.auth_number,
      auth_type: auth.auth_ref.auth_type,
    };
    combinedAuths.push(newAuth);
  });  
});

// 从用户的动态权限中得到权限，放入 combinedAuths 数组里
data.appDynamicsAuths_arr.forEach(dynAuth => {
  let newAuth = {
    auth_id: dynAuth.authID._id,
    auth_name: dynAuth.authID.auth_name,
    auth_desc: dynAuth.authID.auth_desc,
    auth_number: dynAuth.authID.auth_number,
    auth_type: dynAuth.authID.auth_type,
    auth_enable: dynAuth.authEnable_bol,
  };
  combinedAuths.push(newAuth);
});

// 对 combinedAuths 数组进行去重处理
combinedAuths = combinedAuths.reduce((acc, cur) => {
  let existItem = acc.find(auth => auth.auth_name === cur.auth_name);
  // 如果存在，且当前权限的 auth_enable 为 true, 则进行更新
  // 如果不存在，直接添加到结果数组中
  if (existItem && cur.auth_enable) {
    let index = acc.lastIndexOf(existItem);
    acc[index] = cur;
  } else if (!existItem) {
    acc.push(cur);
  }
  
  return acc;
}, []);

data.appAuths = combinedAuths




    } catch (error) {
      console.log(error);
      createResponse(res,500,businessCodes.b2)
      return
    } 
    createResponse(res,200,businessCodes.b1,data)
  }
  )

  
  



  
  
 

  
  
  //#endregion

  module.exports= userRoles